<template>
  <section class="todoapp">
    <TodoListHeader @addList="addList"></TodoListHeader>
    <TodoListBody
      :list="renderList"
      @changFlag="changFlag"
      @delList="delList"
      @changeAll="changeAll"
    ></TodoListBody>
    <TodoListFooter
      :sum="sum"
      :showClearBtn="showClearBtn"
      @delAll="delAll"
      :type="type"
      @changeType="changeType"
    ></TodoListFooter>
  </section>
</template>

<script>
import TodoListHeader from './components/TodoListHeader.vue'
import TodoListBody from './components/TodoListBody.vue'
import TodoListFooter from './components/TodoListFooter.vue'
export default {
  components: {
    TodoListHeader,
    TodoListBody,
    TodoListFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('list')) || [
        {
          id: 1,
          value: '行万里路',
          flag: true,
        },
        {
          id: 2,
          value: 'ikun',
          flag: false,
        },
      ],
      type: 'all',
    }
  },
  //定义方法
  methods: {
    addList(value) {
      this.list = [
        {
          id: +new Date(),
          flag: false,
          value,
        },
        ...this.list,
      ]
    },
    delList(id) {
      //提取要操作的事件
      const event = this.list.find((item) => item.id === id)
      //判断是否完成，如果未完成则不能删除
      if (!event.flag) return alert('没做完呢别删')
      //删除
      this.list = this.list.filter((item) => item.id !== id)
    },
    changFlag(id, flag) {
      this.list.forEach((item) => {
        if (item.id === id) {
          item.flag = flag
        }
      })
    },
    delAll() {
      this.list = this.list.filter((item) => !item.flag)
    },
    //修改type筛选类型
    changeType(value) {
      this.type = value
    },
    changeAll(flag) {
      this.list.forEach((item) => {
        item.flag = flag
      })
    },
  },
  //计算
  computed: {
    //计算未完成的总数
    sum() {
      return this.list.filter((item) => !item.flag).length
    },
    //数据列表中是否包含已完成的事件
    showClearBtn() {
      return this.list.some((item) => item.flag)
    },
    renderList() {
      switch (this.type) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter((item) => !item.flag)
        case 'completed':
          return this.list.filter((item) => item.flag)
        default:
          return this.list
      }
    },
  },
  watch: {
    list: {
      deep: true,
      handler(newVal) {
        localStorage.setItem('list', JSON.stringify(newVal))
      },
    },
  },
}
</script>

<style></style>
